package com.jeecg.p3.system.poster.web;

import com.jeecg.p3.base.util.*;
import com.jeecg.p3.commonweixin.entity.MyJwWebJwid;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Course;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.poster.entity.*;
import com.jeecg.p3.system.poster.service.ExamPaperService;
import com.jeecg.p3.system.poster.service.ExamQuestionBankService;
import com.jeecg.p3.system.poster.service.ExamQuestionService;
import com.jeecg.p3.system.poster.service.ExamResultService;
import com.jeecg.p3.system.service.CourseService;
import com.jeecg.p3.system.service.MyJwWebJwidService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 *
 * @ClassName: ExamResultController
 * @Description: TODO 考试结果控制层
 * @author: zhangxiao
 * @date: 2020年12月8日 下午7:29:38
 */
@Controller
@RequestMapping("/system/back/poster/examResult")
public class ExamResultController extends BaseController {
    public final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ExamResultService service;
    @Autowired
    private CourseService courseService;
    @Autowired
    private ExamQuestionService examQuestionService;
    @Autowired
    private ExamPaperService examPaperService;
    @Autowired
    private MyJwWebJwidService myJwWebJwidService;

    /**
     *
     * @param query 分页查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute ExamResult query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<ExamResult> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        pageQuery.setQuery(query);
        velocityContext.put("examResult",query);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        String viewName = "system/back/exam/exam_result_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 首先根据课程id查询该课程是否有考试试卷信息，如果有试卷信息将试卷信息的试题，答案进行遍历
     * @param request
     * @param response
     * @param courseId 课时id
     * @throws Exception
     */
    @RequestMapping(value = "/toStartExam",method ={RequestMethod.GET, RequestMethod.POST})
    public void toStartExam(HttpServletRequest request, HttpServletResponse response, String courseId)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String toUrl = ComCode.systemUrl + "/system/back/poster/examResult/toStartExam?courseId=" + courseId;
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        String openId = wxUserInfo.getOpenid();
        Course course = courseService.queryById(Long.valueOf(courseId));
        Boolean isHave = false;//该课时是否有正确试题
        if(course != null) {
            ExamQuestion param = new ExamQuestion();
            param.setCourse(course);
            List<ExamQuestion> examQuess = examQuestionService.findByParam(param);
            if(examQuess != null && examQuess.size() == 1) {
                ExamQuestion examQuestion = examQuess.get(0);
                /*判断该人已答题，直接进入答题结果（暂时不用）
                ExamResult resultParam = new ExamResult();
                resultParam.setUserOpenId(openId);
                resultParam.setExamQues(examQuestion);
                List<ExamResult> results = service.findByParam(resultParam);
                if(results != null && results.size() == 1) {
                    toResult(response, request, courseId);
                    return;
                }*/
                List<ExamPaper> paperList = new ArrayList<>();
                String[] papers = examQuestion.getExamPaperIds().split(",");//试题数组
                List<String> paperIdList = new ArrayList<>(Arrays.asList(papers));
                List<String> newIdList = new ArrayList<>();
                for(int i = 5; i > 0; i--) {
                    Random random = new Random();
                    Math.random();
                    int j = random.nextInt(paperIdList.size()-1);//在数组大小之间产生一个随机数 j
                    if(StringUtils.isEmpty(paperIdList.get(j))) {
                        i++;//如果试卷id为空重新筛选
                    } else {
                        newIdList.add(paperIdList.get(j));//取得list 中下标为j 的数据存储到 listRandom 中
                        paperIdList.remove(j);////把已取到的数据移除,避免下次再次取到出现重复
                    }

                }
                //遍历添加试题到列表中
                for(String paperId: newIdList) {
                    ExamPaper examPaper = examPaperService.findPaperAndAnswerById(paperId);
                    if(examPaper != null) {
                        paperList.add(examPaper);
                    }
                }
                examQuestion.setPaperList(paperList);//添加试题列表到试卷中
                isHave = true;
                velocityContext.put("examQuestion", examQuestion);//试卷信息返回到前台
            }
        }
        velocityContext.put("isHave", isHave);
        String viewName = "system/back/exam/exam_start.html";//跳转到开始考试界面
        ViewVelocity.view(request,response,viewName,velocityContext);
    }


    /**
     * 保存信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson doAdd(@ModelAttribute ExamResult examResult, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            WxUserInfo wxUserInfo = getWxUserInfo(request);
            if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
                j.setSuccess(false);
                j.setMsg("微信未授权，请微信授权后再进行答题！");
                return j;
            }
            String openId = wxUserInfo.getOpenid();
            Integer errorNum = 0;//错题数
            Integer successNum = 0;//对题数
            Integer grades = 0;//成绩
            List<ExamResultDetail> details = examResult.getDetailList();
            for(ExamResultDetail detail: details) {
                ExamPaper examPaper = examPaperService.findById(detail.getExamPaper().getId());
                if(examPaper.getAnswer().getId().equals(detail.getMyAnswer().getId())) {
                    detail.setIsCorrect("1");
                    successNum = successNum + 1;//正确题数累加
                } else {
                    detail.setIsCorrect("0");
                    errorNum = errorNum + 1;//错题数累加
                }
            }
            grades = successNum * 20;
            examResult.setUserOpenId(openId);
            examResult.setGrades(grades.toString());
            examResult.setErrorNum(errorNum);
            examResult.setSuccessNum(successNum);
            service.doAdd(examResult);
            j.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }

    /**
     * 跳转查看考试详情界面
     * @return
     */
    @RequestMapping(value="/toResult",method = RequestMethod.GET)
    public void toResult(HttpServletResponse response, HttpServletRequest request, String courseId, String dataTime) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        log.info("url------>" + request.getRequestURL().toString());
        String viewName = "system/back/exam/exam_detail.html";//跳转到考试结果界面
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl = ComCode.systemUrl + "/system/back/poster/examResult/toResult.do?courseId=" + courseId + "&dataTime=" + dataTime;
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            String value = request.getParameter(name);
            System.out.println(name + "=" + value);
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            logger.info("------检测到有code进行再次跳转！！！");
            response.sendRedirect(toUrl);
            return;
        }*/
        Map<String, Object> share = new HashMap<>();//分享数据
        share.put("context", "学中医，没毛病");
        share.put("url", toUrl);
        share.put("imgUrl", ComCode.systemUrl + "/profile/system/system.png");
        velocityContext.put("appId", ComCode.appid);
        MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(Constants.wxid);
        String jsapi_ticket = myJwWebJwid.getJsApiTicket();
        Map<String, String> map = JsSignUtil.sign(jsapi_ticket, toUrl);
        velocityContext.put("wx",map);
        String openId = wxUserInfo.getOpenid();
        Course course = courseService.queryById(Long.valueOf(courseId));
        velocityContext.put("course",course);
        ExamQuestion param = new ExamQuestion();
        param.setCourse(course);
        List<ExamQuestion> examQuess = examQuestionService.findByParam(param);
        if(examQuess != null && examQuess.size() == 1) {
            log.info("已经考试，查看考试信息！！！");
            ExamQuestion examQuestion = examQuess.get(0);
            String title = examQuestion.getCourse().getCourseName();
            ExamResult resultParam = new ExamResult();
            resultParam.setUserOpenId(openId);
            resultParam.setExamQues(examQuestion);
            List<ExamResult> results = service.findByParam(resultParam);
            if(results != null && results.size() > 0) {
                ExamResult examResult = results.get(0);
                if(StringUtils.isNotEmpty(examResult.getGrades())) {
                    Integer baseNum = 200000;
                    Integer count = service.count(new ExamResult());//考试人数
                    Integer grades = Integer.valueOf(examResult.getGrades());
                    String joinNum = String.valueOf(baseNum + count);//参与人数
                    if(grades == 100) {
                        velocityContext.put("isShowSort", true);
                        String mingCi = "1";//名次
                        velocityContext.put("mingCi", mingCi);
                        velocityContext.put("joinNum", joinNum);
                        title = "我在《" + title + "》中考了100分，排名第一！";
                    } else if(grades >= 80) {
                        ExamResult examParam = new ExamResult();
                        examParam.setGrades(grades.toString());
                        Integer countNum = service.count(examParam);//超过80分人数
                        if(countNum == 0) {
                            velocityContext.put("isShowSort", true);
                            String mingCi = "1";//名次
                            velocityContext.put("mingCi", mingCi);
                            velocityContext.put("joinNum", joinNum);
                            title = "我在《" + title + "》中考了" + grades + "分，排名第一！";
                        } else {
                            velocityContext.put("isShowSort2", true);
                            velocityContext.put("mingCi", countNum.toString());
                            velocityContext.put("joinNum", joinNum);
                            velocityContext.put("bili", (count - countNum + baseNum) * 100 / (count + baseNum));
                            title = "我在《" + title + "》中考了" + grades + "分，排名第一！";
                        }
                    } else {
                        title = "我在《" + title + "》中考了" + grades + "分，排名18996！";
                        log.info("考试成绩过低！！！");
                    }
                }
                ExamResultDetail detailsParam = new ExamResultDetail();
                detailsParam.setExamResultId(examResult.getId());
                List<ExamResultDetail> details = service.findByParam(detailsParam);
                examResult.setDetailList(details);
                ExamResultDetail errorDetailParam = new ExamResultDetail();
                errorDetailParam.setExamResultId(examResult.getId());
                errorDetailParam.setIsCorrect("0");
                List<ExamResultDetail> errorDetails = service.findByParam(errorDetailParam);
                examResult.setErrorList(errorDetails);
                velocityContext.put("isHave", true);
                velocityContext.put("examResult", examResult);
                log.info("考试成绩数据结束");
            } else {
                toStartExam(request, response, courseId);
                return;
            }
            share.put("title", title);
        } else {
            velocityContext.put("isHave", false);
            toStartExam(request, response, courseId);
            return;
        }
        velocityContext.put("share", share);
        ViewVelocity.view(request,response,viewName,velocityContext);
    }
}
